package com.iostream;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @Author WaveHi
 * @Date 20/8/2021 下午 4:37
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Test the use of java.io.RandomAccessFile
 */
public class TestRandomAccessFile {

    public static void main(String[] args) {
        RandomAccessFile raf1 = null;

        try {
            //获取存取的位置
            File destFile1 = new File("day11/txt/hello.txt");

            //获取需存取的数据
            String s1 = new String("Wow!");

            //获取流
            raf1 = new RandomAccessFile(destFile1,"rw");

            //数据的存取
            byte[] b = new byte[1024];
            int len = 0;
            StringBuilder s2 = new StringBuilder((int) destFile1.length());
            raf1.seek(0);
            while((len = raf1.read(b)) != -1) {

                s2.append(new String(b,0,len));

            }
            raf1.seek(0);
            raf1.write(s1.getBytes());
            raf1.write(new String(s2).getBytes());

            System.out.println("Data transfer completed!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源的关闭
            if(raf1 != null) {

                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }

}
